package cn.kgcnews.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;

import cn.kgcnews.pojo.NewsComment;
import cn.kgcnews.pojo.NewsDetail;
import cn.kgcnews.service.NewsService;
import cn.kgcnews.service.impl.CommentServiceImpl;
import cn.kgcnews.service.impl.NewsServiceImpl;
import cn.kgcnews.utils.StringUtils;

public class newsReadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doNewsRead(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		NewsService newsService = new NewsServiceImpl();
		String id = request.getParameter("newsid");
		session.setAttribute("newid", id);
		// 正则表达式
		PrintWriter out = response.getWriter();
		String regex = "[0-9]+";
		boolean flag = Pattern.matches(regex, id);
		if (!flag) {
			out.println("<script>alert('传输数据有误');location.href='index.jsp';</script>");
		} else {
			NewsDetail news = newsService.showNewsDetail(id);
			if (news == null) {
				out.println("<script>alert('传输数据有误');location.href='index.jsp';</script>");
			} else {
				
				session.setAttribute("news", news);
				
				session.setAttribute("id", news.getId());
				response.sendRedirect("/chinanews/newsread.jsp");
			}
		}
		out.flush();
		out.close();
	}

	public void newsAdd(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		PrintWriter out = response.getWriter();
		boolean isOK = false; // 图片上传是否成功
		boolean isOnlyText = false; // 是否为文字新闻
		String uploadPath = request.getServletContext().getRealPath("/")
				+ File.separator + "upload";
		// 如果目录不存在则创建
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		NewsDetail news = new NewsDetail();
		// 1:判断表单提交的内容形式
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			// 2:创建文件上传所需的API实例
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 3:解析request请求，获取FileItem对象集合
			List<FileItem> list = upload.parseRequest(request);
			// 4:循环遍历集合中的数据
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 对象为普通表单
					String fieldName = item.getFieldName();
					if ("ntitle".equals(fieldName)) {
						news.setTitle(item.getString("UTF-8"));
					} else if ("nsummary".equals(fieldName)) {
						news.setSummary(item.getString("UTF-8"));
					} else if ("ntid".equals(fieldName)) {
						news.settId(Integer.valueOf(item.getString("UTF-8")));
					} else if ("nauthor".equals(fieldName)) {
						news.setAuthor(item.getString("UTF-8"));
					} else if ("ncontent".equals(fieldName)) {
						news.setContent(item.getString("UTF-8"));
					}
				} else {
					// 对象为文件表单
					String name = item.getName();
					if (name != null && !"".equals(name)) {
						// 控制文件的上传的类型
						if (!StringUtils.checkImg(name)) {
							out.println("<script>alert('新闻图片的格式不正确，请重新选择');history.back();</script>");
						} else {
							String fileName = StringUtils.getNewName(name);
							news.setPicPath(fileName);
							// 远程服务器的文件地址
							File file = new File(uploadPath, fileName);
							item.write(file);
							isOK = true;
						}
					} else {
						isOnlyText = true;
					}

				}

			}
		}
		if (isOnlyText || isOK)

		{
			// 调用业务逻辑层
			NewsService newsService = new NewsServiceImpl();
			news.setCreateDate(new Date());
			boolean result = newsService.publishNews(news);

			if (result) {
				// 发布成功
				out.println("<script>alert('恭喜您，新闻发布成功');location.href='newslist.jsp';</script>");
				// 发布失败
			} else {
				out.println("<script>alert('发布失败');history.back();</script>");
			}
		}

	}



	public void delect(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		NewsServiceImpl n = new NewsServiceImpl();
		PrintWriter out = response.getWriter();
		String ind = request.getParameter("niddd");
		// System.out.println("1111111111111111111111111:"+request.getAttribute("niddd"));
		boolean flag = n.delDetailByNid(Integer.valueOf(ind));
		if (flag) {
			out.println("<script>alert('删除成功');location.href='newslist.jsp';</script>");
		} else {
			out.println("<script>alert('删除失败');location.href='newslist.jsp';</script>");
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		// 优先接受处理的参数
		String action = request.getParameter("action");
		System.out.println(action);
		if (action != null && !action.equals("")) {
			if (action.equals("newsread")) {
				System.out.println("999999999999999999999999999999");
				this.doNewsRead(request, response);
				//this.findNewsComment(request, response);
			} else if (action.equals("newsadd")) {
				try {
					this.newsAdd(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (action.equals("del")) {

				this.delect(request, response);
			}
		} else {
			 //this.findNewsComment(request, response);
			response.sendRedirect("newsread.jsp");

		}

	}

	public void init() throws ServletException {

	}

}
